<template>
  <div class="page-wrap1">
    <div class="card">
      <div class="icon-top"></div>
      <div class="card-content">
        <div class="card-data">
          <div class="card-item">
            <div class="iconfont icon-enterprise"></div>
            <div class="title">企业名称</div>
            <div class="card-value">
              {{ data.detailData ? data.detailData.accountName : '--' }}
            </div>
          </div>
          <div class="card-item">
            <div class="iconfont icon-wallet1"></div>
            <div class="title">钱包余额</div>
            <div class="card-value">
              ￥{{ data.detailData ? data.detailData.unitBalance : '--' }}
            </div>
          </div>
        </div>
      </div>
      <div class="card-content1">
        <div class="button-list">
          <el-button
            v-if="bntAuth(`${key}.recharge`)"
            type="primary"
            plain
            class="button-item recharge"
            @click="recharge(8)"
          >
            <div class="iconfont icon-recharge"></div>
            充值</el-button
          >
          <el-button
            v-if="bntAuth(`${key}.refund`)"
            type="primary"
            plain
            class="button-item refund"
            @click="recharge(9)"
          >
            <div class="iconfont icon-refund"></div>
            退款</el-button
          >
          <div class="button-item back" @click="back">
            <div class="iconfont icon-back"></div>
            返回
          </div>
        </div>
      </div>
      <div class="icon-bottom"></div>
    </div>
    <!-- 弹窗开始 -->
    <el-dialog
      v-model="dialogVisible"
      :title="ruleForm.type == 8 ? '充值' : '退款'"
      width="430"
      class="qc-custom-dialog"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="70px"
        class="dialog-form-wrap"
      >
        <div class="has-tips">
          <div class="tip">
            <div class="icon"></div>
            {{
              ruleForm.type == 8
                ? '提示：当前企业需完成线下打款后，平台通过此操作将充值金额同步更新至企业钱包。'
                : '提示：平台已经线下对当前企业执行了退款操作后，通过此操作将退款金额同步在钱包中扣除'
            }}
          </div>
        </div>
        <el-form-item
          :label="ruleForm.type == 8 ? '充值金额' : '退款金额'"
          prop="amount"
        >
          <el-input
            v-model.trim="ruleForm.amount"
            :placeholder="
              ruleForm.type == 8 ? '请输入充值金额' : '请输入退款金额'
            "
            maxlength="30"
            clearable
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model.trim="ruleForm.remark"
            placeholder="请输入备注"
            maxlength="200"
            type="textarea"
            :rows="3"
            show-word-limit
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="hide">取消</el-button>
          <el-button type="primary" v-btnAntiShake="onSubmit"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 弹窗结束 -->
    <Head title="钱包流水" v-if="data.accountId">
      <template #content>
        <Table
          ref="tableRef"
          :columns="data.columns"
          :toolbar="data.toolbar"
          :query="data.query"
          @get-list="getData"
        ></Table>
      </template>
    </Head>
  </div>
</template>
   
<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import Head from '@/components/head/index.vue';
import Table from '@/components/table/index.vue';
import {
  pagingAccountFlow,
  getAccount,
  changeAccount,
  EXPORT_ACCOUNTFLOW,
} from '@/service/apis/enterprise';
import { queryDicByParent } from '@/service/apis/api';
import { FLOW_TYPE } from '@/utils/dictionaries';
import { IS_NUM_MORE0 } from '@/utils/verify';
import { getTime, bntAuth, exportFile } from '@/utils/utils';

const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const tableRef = ref();
const {
  query: { id, key },
} = route;

let dialogVisible = ref(false);
const ruleForm = reactive({
  paymentType: 1,
  type: 9,
  amount: '',
  remark: '',
  accountId: undefined as unknown,
  workTime: '',
});
const rules = reactive<FormRules>({
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    {
      pattern: IS_NUM_MORE0,
      message: '请输入正确的金额',
      trigger: 'blur',
    },
  ],
  remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
});
const data = reactive({
  detailData: {} as any,
  accountId: false,
  columns: [
    {
      label: '流水号',
      prop: 'billId',
    },
    {
      label: '流水类型',
      prop: 'type',
      dic: [] as any,
      type: Number,
    },
    {
      label: '流水金额（元）',
      prop: 'amount',
    },
    {
      label: '备注',
      prop: 'remark',
    },
    {
      label: '执行人',
      prop: 'createBy',
    },
    {
      label: '流水时间',
      prop: 'createTime',
    },
  ],
  toolbar: [
    {
      label: '导出',
      permission: 'enterpriseList.export',
      icon: 'icon-export',
      type: 'primary',
      plain: true,
      handle: (row: any) => {
        exportFile(
          EXPORT_ACCOUNTFLOW,
          '企业账户流水',
          tableRef.value?.getForm()
        );
      },
    },
  ],
  query: [
    {
      label: '流水类型',
      prop: 'type',
      comName: 'select',
      props: {
        placeholder: '请选择流水类型',
        options: [] as any,
      },
    },
    {
      label: '流水时间',
      prop: 'date',
      comName: 'date',
      props: {
        type: 'daterange',
      },
    },
  ],
});

const back = () => {
  router.go(-1);
};

queryDicByParent({
  listDtos: ['accountFlowType', 'paymentType'],
}).then((res: any) => {
  if (res) {
    const accountFlowType = res.accountFlowType.filter(
      (item: { value: number }) =>
        item.value == 9 || item.value == 6 || item.value == 7 || item.value == 8
    );
    data.query[0].props.options = [...accountFlowType];
    data.columns[1].dic = [...res.accountFlowType];
  }
});

// 获取
const getAccountData = () => {
  getAccount({
    originalAccountId: id,
    accountType: '1',
  }).then((res: any) => {
    data.detailData = res;
    if (data.detailData.id) {
      data.accountId = true;
    }
  });
};
getAccountData();

// 钱包流水查询
const getData = (page: any, search: any) => {
  nextTick(() => {
    let form: any = search.ruleForm;
    console.log('search=====', search.ruleForm);

    if (
      search.ruleForm &&
      search.ruleForm.date &&
      search.ruleForm.date.length > 1
    ) {
      form.startTime = search.ruleForm.date[0];
      form.endTime = search.ruleForm.date[1];
    } else {
      form.startTime = '';
      form.endTime = '';
    }
    form.accountId = data.detailData?.id;
    pagingAccountFlow(form, page).then((res: any) => {
      if (res) {
        if (
          page.pageNo !== 1 &&
          (!res.dataList || res.dataList?.length === 0)
        ) {
          page.pageNo--;
          getData(page, search);
          return;
        }
        nextTick(() => {
          tableRef.value.setTable({
            total: res.totalCount,
            table: res.dataList,
          });
        });
      }
    });
  });

  // let startTime = '';
  // let endTime = '';
  // let type = '';
  // if (
  //   search.ruleForm &&
  //   search.ruleForm.date &&
  //   search.ruleForm.date.length > 1
  // ) {
  //   startTime = search.ruleForm.date[0];
  //   endTime = search.ruleForm.date[1];
  // }
  // if (search.ruleForm && search.ruleForm.type) {
  //   type = search.ruleForm.type;
  // }
  // if (!data.detailData.id) {
  //   getAccount({
  //     originalAccountId: id,
  //     // originalAccountId: '1656189216788058113',
  //     accountType: '1',
  //   }).then((res: any) => {
  //     data.detailData = res;
  //     if (res.id) {
  //       pagingAccountFlow(
  //         {
  //           accountId: res?.id,
  //           startTime,
  //           endTime,
  //           type: Number(type),
  //         },
  //         page
  //       ).then((res: any) => {
  //         nextTick(() => {
  //           tableRef.value.setTable({
  //             total: 1,
  //             table: res.dataList,
  //           });
  //         });
  //       });
  //     }
  //   });
  // } else {
  //   pagingAccountFlow(
  //     {
  //       accountId: data?.detailData?.id,
  //       startTime,
  //       endTime,
  //       type: Number(type),
  //     },
  //     page
  //   ).then((res: any) => {
  //     nextTick(() => {
  //       tableRef.value.setTable({
  //         total: 1,
  //         table: res.dataList,
  //       });
  //     });
  //   });
  // }
};

// 关闭弹框
const hide = () => {
  dialogVisible.value = false;
};
// 打开弹窗并赋值
const recharge = (value: number) => {
  dialogVisible.value = true;
  ruleForm.amount = '';
  ruleForm.remark = '';
  ruleForm.type = Number(value);
  nextTick(() => {
    ruleFormRef.value?.clearValidate();
  });
};

// 充值/退款确认
const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  const form = { ...ruleForm };
  let time = new Date();
  // ruleForm.accountId = data?.detailData?.id;
  form.accountId = data?.detailData?.id;
  form.workTime = getTime(time);
  console.log(form.workTime);
  changeAccount(form).then((res: any) => {
    console.log('res===', res);
    emit('clear-cache');
    hide();
    getAccountData();
    tableRef.value?.handleQuery();
  });
};
</script>  
<style lang="scss">
@import '@/assets/styles/head.scss';
</style>

<style lang="scss" scoped>
.card {
  background: linear-gradient(180deg, #5073f7 0%, #2e52db 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  position: relative;
  z-index: 99;
  padding: 20px 0 14px 0;
  margin-bottom: 20px;
  transform: matrix(1, 0, 0, 1, 0, 0);
  .icon-top {
    &::after {
      content: '';
      background-image: url(@/assets/images/left-bg.png);
      background-repeat: no-repeat;
      background-size: cover;
      opacity: 0.2;
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 80%;
    }
  }
  .icon-bottom {
    &::after {
      content: '';
      background-image: url(@/assets/images/right-bg.png);
      // background-size: 100%;
      background-repeat: no-repeat;
      background-size: cover;
      opacity: 0.2;
      position: absolute;
      top: 0;
      left: 80%;
      bottom: 0;
      right: 0;
      z-index: -1;
    }
  }
  .card-content {
    margin-left: 20%;
    width: 30%;
    .card-data {
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #ffff;
      align-items: center;
      .card-item {
        text-align: center;
        .iconfont {
          font-size: 36px;
          line-height: 36px;
        }
        .title {
          font-size: 13px;
          font-weight: 700;
          line-height: 20px;
          margin-top: 2px;
        }
        .card-value {
          font-size: 13px;
          font-weight: 500;
          line-height: 22px;
          margin-top: 2px;
        }
      }
    }
  }
  .card-content1 {
    position: absolute;
    right: 26px;
    .button-list {
      display: flex;
      .button-item {
        display: flex;
        flex-direction: row;
        align-items: flex-start;
        padding: 6px 30px;
        gap: 4px;
        background: #ffffff;
        border-radius: 8px;
        font-weight: 400;
        font-size: 13px;
        line-height: 20px;
        margin-right: 10px;
        cursor: pointer;
      }
      .recharge {
        color: #5073f7;
      }
      .refund {
        color: #fa3939;
      }
      .back {
        color: #5073f7;
      }
    }
  }
}
</style>